package com.lyl.servicecms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lyl.servicecms.entity.Banner;
import com.lyl.servicecms.mapper.BannerMapper;
import com.lyl.servicecms.service.BannerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 首页banner表 服务实现类
 * </p>
 *
 * @author 雷艳玲
 * @since 2022-06-17
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {
    //查询所有banner
    // 缓存到redis中去 值为banner::selectIndexList
    @Cacheable(value = "banner",key = "'selectIndexList'")
    @Override
    public List<Banner> selectAllBanner() {

        //根据id进行降序排列，显示排列之后前两条记录
        QueryWrapper<Banner> wrapper = new QueryWrapper<>();
        wrapper.eq("is_disabled",false);
        wrapper.orderByDesc("id");
        //last方法，拼接sql语句
        wrapper.last("limit 4");
        List<Banner> list = baseMapper.selectList(wrapper);
        return list;
    }

    /**
     * 添加了新图片之后, 把缓存清空
     * @param banner
     * @return
     */
    @CacheEvict(value = "banner",key = "'selectIndexList'",allEntries = true)
    @Transactional
    @Override
    public boolean addBanner(Banner banner){
        return baseMapper.insert(banner)>0;
    }

    @CacheEvict(value = "banner",key = "'selectIndexList'",allEntries = true)
    @Transactional
    @Override
    public boolean updateBanner(Banner banner){
        return baseMapper.updateById(banner)>0;
    }

    @Override
    @CacheEvict(value = "banner",key = "'selectIndexList'",allEntries = true)
    @Transactional
    public boolean updateStatusById(Long id, Boolean bannerStatus) {
//        UpdateWrapper<Banner> updateWrapper= new UpdateWrapper<>();
//        updateWrapper.eq("id",id);
//        updateWrapper.set("is_disabled",bannerStatus);
        Banner banner= new Banner();
        banner.setId(id);
        banner.setIsDisabled(bannerStatus);

        return  baseMapper.updateById(banner)>0;
    }

    @CacheEvict(value = "banner",key = "'selectIndexList'",allEntries = true)
    @Transactional
    @Override
    public boolean deleteBanner(Long id){
        return baseMapper.deleteById(id)>0;
    }
}
